package com.hongpu.config;


import com.github.benmanes.caffeine.cache.Caffeine;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.caffeine.CaffeineCacheManager;
import org.springframework.cache.support.CompositeCacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;

import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author  张玉胜
 */
@Configuration
@EnableCaching // 开启缓存
public class CacheConfig {
    // 缓存配置 初始化缓存数量
    private static final int INITIAL_CAPACITY = 10000;
    // 缓存配置 最大缓存数量
    private static final int MAXIMUM_SIZE = 10000;
    // 缓存配置 过期时间
    private static final int EXPIRE_SECONDS = 3600;

    @Bean
    public CacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) {
        /**
         * 一级缓存(本地)
         */
        Caffeine<Object, Object> cacheConfig = Caffeine.newBuilder();
        cacheConfig.initialCapacity(INITIAL_CAPACITY)
                .maximumSize(MAXIMUM_SIZE)
                .expireAfterWrite(EXPIRE_SECONDS, TimeUnit.SECONDS)
                .recordStats()  // 启用统计缓存信息
        ;
        // 在这里设置缓存名称集合
        List<String> cacheNames = Arrays.asList("oaCacheKey");
        CaffeineCacheManager caffeineCacheManager = new CaffeineCacheManager();
        caffeineCacheManager.setCaffeine(cacheConfig);
        caffeineCacheManager.setCacheNames(cacheNames);

        /**
         * 二级缓存(Redis)
         */
        RedisCacheManager redisCacheManager = RedisCacheManager.create(redisConnectionFactory);
        // 组合一级和二级缓存
        return  new CompositeCacheManager(caffeineCacheManager,redisCacheManager);
     }
}